<template>
  <div class="production-line-container">
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
    </div>

    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" width="60" />
      <el-table-column prop="code" label="编号" width="120">
        <template #default="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.code"
            size="small"
            placeholder="请输入编号"
          />
          <span v-else>{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="180">
        <template #default="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.name"
            size="small"
            placeholder="请输入名称"
          />
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="workshop" label="所属车间" width="180">
        <template #default="scope">
          <el-select
            v-if="scope.row.isEdit"
            v-model="scope.row.workshop"
            size="small"
            placeholder="请选择车间"
          >
            <el-option
              v-for="item in workshopOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <span v-else>{{ scope.row.workshop }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述">
        <template #default="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.description"
            size="small"
            placeholder="请输入描述"
            type="textarea"
          />
          <span v-else>{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="创建人" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <div v-if="scope.row.isEdit">
            <el-button type="primary" link @click="handleSave(scope.row)">保存</el-button>
            <el-button type="danger" link @click="handleCancel(scope.row)">取消</el-button>
          </div>
          <div v-else>
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增生产线' : '编辑生产线'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="所属车间" prop="workshop">
          <el-select v-model="formData.workshop" placeholder="请选择车间" style="width: 100%">
            <el-option
              v-for="item in workshopOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add or edit
const formRef = ref(null)
const formData = reactive({
  id: '',
  code: '',
  name: '',
  workshop: '',
  description: ''
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  workshop: [{ required: true, message: '请选择所属车间', trigger: 'change' }]
}

// 车间选项
const workshopOptions = ref([
  { value: '灌装车间', label: '灌装车间' },
  { value: '1号车间', label: '1号车间' },
  { value: '一号车间', label: '一号车间' },
  { value: '灌装车间(8)', label: '灌装车间(8)' },
  { value: '灌装车间222swx', label: '灌装车间222swx' }
])

// 初始化数据
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    // 生成当前一星期内的日期
    const generateRecentDates = (index) => {
      const now = new Date()
      // 创建时间：当前日期往前推 (index % 5 + 2) 天
      const createDate = new Date(now)
      createDate.setDate(now.getDate() - (index % 5 + 2))
      const createTime = createDate.toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
      
      // 更新时间：创建时间往后推2天
      const updateDate = new Date(createDate)
      updateDate.setDate(createDate.getDate() + 2)
      const updateTime = updateDate.toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
      
      return { createTime, updateTime }
    }

    const mockData = [
      {
        id: 1,
        code: 'KLGZ001999',
        name: '颗粒灌装线 213jx',
        workshop: '颗粒灌装线hhh',
        description: '运营线往上有七个工位',
        creator: '(test)AAA',
        ...generateRecentDates(1)
      },
      {
        id: 2,
        code: 'GY001',
        name: '颗粒灌装线(5)',
        workshop: '灌装车间(8)',
        description: '车间负责人：小宋 地址：北京海淀区产线 mint场景标签：灌装 产线；名称：颗粒灌装线 编号：GY001 负责人：小宋 状态：启用',
        creator: '(test)AAA',
        ...generateRecentDates(2)
      },
      {
        id: 3,
        code: 'GY001',
        name: '颗粒灌装线（D）',
        workshop: '灌装车间(8)',
        description: '车间负责人：小宋 地址：北京海淀区产线 mint场景标签：灌装 产线；名称：颗粒灌装线 编号：GY001 负责人：小宋 状态：启用',
        creator: '(test)AAA',
        ...generateRecentDates(3)
      },
      {
        id: 4,
        code: 'KL001',
        name: '颗粒灌装线',
        workshop: '1号车间',
        description: 'mint场景标签：灌装 产线负责人：小王',
        creator: '(test)AAA',
        ...generateRecentDates(4)
      },
      {
        id: 5,
        code: 'KL001',
        name: '颗粒灌装线(2)',
        workshop: '1号车间',
        description: 'mint场景标签：灌装 产线负责人：小王',
        creator: '(test)AAA',
        ...generateRecentDates(5)
      }
    ]
    
    // 添加更多模拟数据以匹配截图中的数据
    const additionalData = [
      {
        id: 6,
        code: 'KL001',
        name: '灌装线工位信息',
        workshop: '一号车间',
        description: '产线负责人：小王',
        creator: '(test)AAA',
        ...generateRecentDates(6)
      },
      {
        id: 7,
        code: 'KLGZ001',
        name: '颗粒灌装线',
        workshop: '灌装车间',
        description: '产线负责人：小明 mint场景标签：灌装 状态：启用',
        creator: '(test)AAA',
        ...generateRecentDates(7)
      },
      {
        id: 8,
        code: 'KL001',
        name: '颗粒灌装线',
        workshop: '一号车间',
        description: '产线负责人：小王',
        creator: '(test)AAA',
        ...generateRecentDates(8)
      },
      {
        id: 9,
        code: 'KLGZ001',
        name: '颗粒灌装线222swx',
        workshop: '灌装车间222swx',
        description: '产线负责人：小明',
        creator: '(test)AAA',
        ...generateRecentDates(9)
      },
      {
        id: 10,
        code: 'KLGZ001',
        name: '颗粒灌装线',
        workshop: '灌装车间',
        description: '产线负责人：小明 mint场景标签：灌装 状态：启用',
        creator: '(test)AAA',
        ...generateRecentDates(10)
      }
    ]
    
    mockData.push(...additionalData)
    
    tableData.value = mockData.map(item => ({
      ...item,
      isEdit: false,
      _originalData: { ...item } // 保存原始数据，用于取消编辑
    }))
    
    total.value = mockData.length
    loading.value = false
  }, 500)
}

// 表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 新增按钮
const handleAdd = () => {
  dialogType.value = 'add'
  formData.id = ''
  formData.code = ''
  formData.name = ''
  formData.workshop = ''
  formData.description = ''
  dialogVisible.value = true
  // 在下一个事件循环中重置表单验证
  setTimeout(() => {
    formRef.value?.resetFields()
  })
}

// 编辑按钮
const handleEdit = (row) => {
  row.isEdit = true
  // 保存原始数据，用于取消编辑
  row._originalData = { ...row }
}

// 保存行内编辑
const handleSave = (row) => {
  // 这里应该调用API保存数据
  ElMessage.success('保存成功')
  row.isEdit = false
  row.updateTime = new Date().toLocaleString()
}

// 取消行内编辑
const handleCancel = (row) => {
  // 恢复原始数据
  Object.keys(row._originalData).forEach(key => {
    if (key !== '_originalData' && key !== 'isEdit') {
      row[key] = row._originalData[key]
    }
  })
  row.isEdit = false
}

// 删除单行
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API删除数据
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      tableData.value.splice(index, 1)
      total.value--
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API批量删除数据
    const ids = selectedRows.value.map(row => row.id)
    tableData.value = tableData.value.filter(item => !ids.includes(item.id))
    total.value -= selectedRows.value.length
    selectedRows.value = []
    ElMessage.success('批量删除成功')
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 新增
        const newId = Math.max(...tableData.value.map(item => item.id)) + 1
        const newRow = {
          id: newId,
          code: formData.code,
          name: formData.name,
          workshop: formData.workshop,
          description: formData.description,
          creator: '(test)AAA',
          createTime: new Date().toLocaleString(),
          updateTime: '',
          isEdit: false
        }
        tableData.value.push(newRow)
        total.value++
        ElMessage.success('添加成功')
      } else {
        // 编辑
        const index = tableData.value.findIndex(item => item.id === formData.id)
        if (index !== -1) {
          tableData.value[index] = {
            ...tableData.value[index],
            code: formData.code,
            name: formData.name,
            workshop: formData.workshop,
            description: formData.description,
            updateTime: new Date().toLocaleString()
          }
          ElMessage.success('编辑成功')
        }
      }
      dialogVisible.value = false
    } else {
      return false
    }
  })
}
</script>

<style scoped>
.production-line-container {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table :deep(.el-table__row) {
  height: 50px;
}
</style>
